package com.langsheng.lsintell.ui.activity;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.langsheng.lsintell.R;
import com.langsheng.lsintell.cmd.request.LSRequest;
import com.langsheng.lsintell.interfaces.LSResDataListener;
import com.langsheng.lsintell.network.LSNet;
import com.langsheng.lsintell.utils.LSUtil;
import com.langsheng.lsintell.utils.encrypt.LSAES256;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * A login screen that offers login via email/password.
 */
public class LSRegisterActivity extends LSBaseActivity {

    @BindView(R.id.identify)
    EditText identify;
    @BindView(R.id.btn_get_identify)
    Button btnGetIdentify;
    @BindView(R.id.email_sign_in_button)
    Button emailSignInButton;
//    private UserRegisterTask mAuthTask = null;

    // UI references.
    private AutoCompleteTextView mPhoneView;
    private EditText mPasswordView;
    private View mProgressView;
    private View mLoginFormView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        ButterKnife.bind(this);
        initTitleView(findViewById(R.id.view_register_title));
        // Set up the login form.
        mPhoneView = (AutoCompleteTextView) findViewById(R.id.phone);
        mPasswordView = (EditText) findViewById(R.id.password);
        mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if (id == R.id.login || id == EditorInfo.IME_NULL) {
                    attemptRegister();
                    return true;
                }
                return false;
            }
        });

        mLoginFormView = findViewById(R.id.login_form);
        mProgressView = findViewById(R.id.login_progress);
    }

    /**
     * Attempts to sign in or register the account specified by the login form.
     * If there are form errors (invalid email, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    private void attemptRegister() {

        // Reset errors.
        mPhoneView.setError(null);
        mPasswordView.setError(null);

        // Store values at the time of the login attempt.
        String email = mPhoneView.getText().toString();
        String password = mPasswordView.getText().toString();

        boolean cancel = false;
        View focusView = null;

        // Check for a valid password, if the user entered one.
        if (TextUtils.isEmpty(password)) {
            mPasswordView.setError(getString(R.string.error_invalid_password));
            focusView = mPasswordView;
            cancel = true;
        }

        if (TextUtils.isEmpty(identify.getText().toString())) {
            identify.setError("验证码不能为空");
            focusView = identify;
            cancel = true;
        }

        // Check for a valid email address.
        if (TextUtils.isEmpty(email)) {
            mPhoneView.setError(getString(R.string.error_invalid_phone));
            focusView = mPhoneView;
            cancel = true;
        } else if (!LSUtil.isChinaPhoneLegal(email)) {
            mPhoneView.setError("手机号输入不正确");
            focusView = mPhoneView;
            cancel = true;
        }

        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            focusView.requestFocus();
        } else {
            // Show a progress spinner, and kick off a background task to
            // perform the user login attempt.
            showProgress(true);
//            mAuthTask = new UserRegisterTask(email, password);
//            mAuthTask.execute((Void) null);
            doRegister();
        }
    }

    private void doRegister() {
        LSRequest request = new LSRequest() {
            @Override
            public void createCmd() {
                setCmdCode(0x2006);
                JSONObject object = new JSONObject();
                object.put("mobile", mPhoneView.getText().toString());
                object.put("mobilecode", identify.getText().toString());
                object.put("password", LSAES256.encryptPwd(mPasswordView.getText().toString()));
                object.put("entype", "0");
                setContent(object.toString());
            }
        };
        LSNet.getInstance().sendRequest(request, true, new LSResDataListener() {
            @Override
            public boolean onResponse(String content) {
			                LSUtil.showToast(LSRegisterActivity.this, "注册成功");
                return false;
            }

            @Override
            public boolean onResponseErr(String errCode, String content) {
                return false;
            }
        });
    }

    /**
     * Shows the progress UI and hides the login form.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

        mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        mLoginFormView.animate().setDuration(shortAnimTime).alpha(
                show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
            }
        });

        mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
        mProgressView.animate().setDuration(shortAnimTime).alpha(
                show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            }
        });
    }

    @OnClick({R.id.btn_get_identify, R.id.email_sign_in_button})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_get_identify:
                if (!LSUtil.isChinaPhoneLegal(mPhoneView.getText().toString())) {
                    mPhoneView.setError(getString(R.string.error_invalid_phone));
                    mPhoneView.requestFocus();
                    return;
                }
                getIdentify(mPhoneView.getText().toString());
                break;
            case R.id.email_sign_in_button:
                attemptRegister();
                break;
        }
    }

    private void getIdentify(String phoneNumber) {
        final JSONObject object = new JSONObject();
        object.put("mobile", phoneNumber);
        LSRequest request = new LSRequest() {
            @Override
            public void createCmd() {
                setCmdCode(0x2005);
                setContent(object.toString());
            }
        };

        LSNet.getInstance().sendRequest(request, true, new LSResDataListener() {
            @Override
            public boolean onResponse(String content) {
                //TODO:倒计时验证码
                return false;
            }

            @Override
            public boolean onResponseErr(String errCode, String content) {
                return false;
            }
        });
    }
}

